<!-- 登录页 -->
<template>
  <div class="container">
    <div class="form">
      <div class="title">
        <span>千锋科技后台管理</span>
      </div>
      <!-- 表单 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="ruleForm.pwd"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >登录</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
// 引入登录得请求接口
import { loginApi } from "@/utils/https";
// 引入setcookie 方法
import { setCookie } from "@/utils/cookie";
export default {
  data() {
    return {
      ruleForm: {
        name: "",
        pwd: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" },
        ],
        pwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 6, message: "长度在6个字符", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      //  登录提交
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log(this.ruleForm);
          loginApi(this.ruleForm).then((res) => {
            console.log(2, res);
            if (res.data.code == 200) {
              //请求成功
              this.$message({
                message: "登录成功",
                type: "success",
                duration: 800,
              });

              //存token 到本地
              setCookie("token", res.data.data.token);
              //存用户信息
              localStorage.setItem("userinfo", res.data.data.name);
              // 存角色信息
              localStorage.setItem("role", res.data.data.role);
              // 跳转到首页
              this.$router.push("/");
            } else {
              //请求失败
              this.$message({
                message: "登录失败",
                type: "error",
                duration: 800,
              });
            }
          });
        } else {
          // console.log(2);
          return false;
        }
      });
    },
    resetForm(formName) {
      // 重置
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style lang='less' scoped>
/* @import url(); 引入css类 */
@import url("../../assets/css/login.less");
</style>